package com.ruoyi.yipaiju.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.enums.dict.OriginName;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yipaiju.domain.*;
import com.ruoyi.yipaiju.mapper.ForeclosedHouseMapper;
import com.ruoyi.yipaiju.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueInformation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * fo_foreclosed_houseService业务层处理
 * 
 * @author liuwp
 * @date 2023-03-01
 */
@Service
public class ForeclosedHouseServiceImpl implements IForeclosedHouseService 
{

    private static final Logger log = LoggerFactory.getLogger(ForeclosedHouseServiceImpl.class);

    @Autowired
    private ForeclosedHouseMapper foreclosedHouseMapper;

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IServerManageService serverManageService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private IHouseEstateService houseEstateService;

    /**
     * 查询fo_foreclosed_house
     * 
     * @param id fo_foreclosed_house主键
     * @return fo_foreclosed_house
     */
    @Override
    public ForeclosedHouse selectForeclosedHouseById(Long id)
    {
        return foreclosedHouseMapper.selectForeclosedHouseById(id);
    }

    /**
     * 查询fo_foreclosed_house列表
     * 
     * @param foreclosedHouse fo_foreclosed_house
     * @return fo_foreclosed_house
     */
    @Override
    public List<ForeclosedHouse> selectForeclosedHouseList(ForeclosedHouse foreclosedHouse)
    {
        return foreclosedHouseMapper.selectForeclosedHouseList(foreclosedHouse);
    }

    /**
     * 根据业务主键查询一条记录：fo_foreclosed_house
     *
     * @param foreclosedHouse fo_foreclosed_house
     * @return fo_foreclosed_house
     */
    @Override
    public ForeclosedHouse selectOneForeclosedHouse(ForeclosedHouse foreclosedHouse)
    {
        return foreclosedHouseMapper.selectOneForeclosedHouse(foreclosedHouse);
    }

    /**
     * 新增fo_foreclosed_house
     * 
     * @param foreclosedHouse fo_foreclosed_house
     * @return 结果
     */
    @Override
    public int insertForeclosedHouse(ForeclosedHouse foreclosedHouse)
    {
        foreclosedHouse.setCreateTime(DateUtils.getNowDate());
        return foreclosedHouseMapper.insertForeclosedHouse(foreclosedHouse);
    }

    /**
     * 修改fo_foreclosed_house
     * 
     * @param foreclosedHouse fo_foreclosed_house
     * @return 结果
     */
    @Override
    public int updateForeclosedHouse(ForeclosedHouse foreclosedHouse)
    {
        foreclosedHouse.setUpdateTime(DateUtils.getNowDate());
        return foreclosedHouseMapper.updateForeclosedHouse(foreclosedHouse);
    }

    @Override
    public int updateForeclosedHouseCondition(ForeclosedHouse foreclosedHouse, ForeclosedHouse foreclosedHouseCondition)
    {
                foreclosedHouse.setUpdateTime(DateUtils.getNowDate());
        return foreclosedHouseMapper.updateForeclosedHouseCondition(foreclosedHouse, foreclosedHouseCondition);
    }

    /**
     * 批量删除fo_foreclosed_house
     * 
     * @param ids 需要删除的fo_foreclosed_house主键
     * @return 结果
     */
    @Override
    public int deleteForeclosedHouseByIds(Long[] ids)
    {
        return foreclosedHouseMapper.deleteForeclosedHouseByIds(ids);
    }

    /**
     * 删除fo_foreclosed_house信息
     * 
     * @param id fo_foreclosed_house主键
     * @return 结果
     */
    @Override
    public int deleteForeclosedHouseById(Long id)
    {
        return foreclosedHouseMapper.deleteForeclosedHouseById(id);
    }

    /**
     * 条件删除fo_foreclosed_house
     *
     * @param foreclosedHouse fo_foreclosed_house
     * @return 结果
     */
    @Override
    public int deleteForeclosedHouseByCondition(ForeclosedHouse foreclosedHouse)
    {
        return foreclosedHouseMapper.deleteForeclosedHouseByCondition(foreclosedHouse);
    }

    @Override
    public void reflushForeclosedHousePosition() {
        /**
         * 刷地址位置
         */
        // 获取线程池 TODO 先不多线程了 接口不让。。。
//        ExecutorService executorService = Executors.newFixedThreadPool(20);
        try {
            while (true){
                try {
                    PageUtils.startPage(1, 100);
                    List<ForeclosedHouse> foreclosedHouses = selectForeclosedHouseList(Builder.of(ForeclosedHouse::new)
                            .with(ForeclosedHouse::setPosition, StringUtils.EMPTY)
//                            .with(ForeclosedHouse::setStatusArr, new String[]{"进行中","预告中","已成交"})
                            .with(ForeclosedHouse::setAddressNE, "true").build());
                    if (foreclosedHouses == null || foreclosedHouses.size() == 0){
                        break;
                    }

                    boolean tmp = true;
                    for (ForeclosedHouse item : foreclosedHouses) {
                        tmp = foreclosedHouseGeocoder(item);
                        Thread.sleep(1000);
                        if (!tmp){
                            break;
                        }
                    }
                    if (!tmp){
                        break;
                    }
//                    foreclosedHouses.forEach(item -> {
//                        executorService.execute(()->{
//                            foreclosedHouseGeocoder(item);
//                        });
//                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
//            executorService.shutdown();
//            while (true) {
//                Thread.sleep(100);
//                if(executorService.isTerminated()){
//                    break;
//                }
//            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void cleanForeclosedHouseData() {
        while (true){
            try {
//                PageUtils.startPage(1, 1000);
                List<ForeclosedHouse> foreclosedHouses = selectForeclosedHouseList(Builder.of(ForeclosedHouse::new)
                        .with(ForeclosedHouse::setCourt, "isNull")
                        .build());
                for (ForeclosedHouse foreclosedHouse : foreclosedHouses) {
                    try {
                        foreclosedHouse = selectForeclosedHouseById(foreclosedHouse.getId());
                        // 洗法院
                        clearForeclosedHouseCourt(foreclosedHouse);
//                        // 洗来源
//                        clearForeclosedHouseOrigin(foreclosedHouse);
//                        // 洗面积
//                        clearForeclosedHouseMianji(foreclosedHouse);

                        updateForeclosedHouse(foreclosedHouse);
                    }catch (Exception e){
                        System.out.println(JSONObject.toJSONString(foreclosedHouse));
                        e.printStackTrace();
                    }
                }
                break;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void timeHandlerForeclosedHouseData() {

        while (true){
            try {
                PageUtils.startPage(1, 1000);
                List<ForeclosedHouse> foreclosedHouses = selectForeclosedHouseList(Builder.of(ForeclosedHouse::new)
                        .with(ForeclosedHouse::setStartTimeStr, "")
                        .build());
                for (ForeclosedHouse foreclosedHouse : foreclosedHouses) {
                    try {
                        foreclosedHouse = selectForeclosedHouseById(foreclosedHouse.getId());

                        // 洗时间
                        clearForeclosedHouseTimeHandler(foreclosedHouse);

                        if (foreclosedHouse.getStartTime() != null){
                            updateForeclosedHouse(foreclosedHouse);
                        }
                        log.info("time_handler result: id="+foreclosedHouse.getId()+", startTime="+foreclosedHouse.getStartTime());
                    }catch (Exception e){
                        System.out.println(JSONObject.toJSONString(foreclosedHouse));
                        e.printStackTrace();
                    }
                }
                if (foreclosedHouses.size() < 1000){
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void cleanForeclosedHouseAreaData(String origin){
//        PageUtils.startPage(1, 100);
        List<ForeclosedHouse> foreclosedHouses = selectForeclosedHouseList(Builder.of(ForeclosedHouse::new)
                .with(ForeclosedHouse::setOrigin, origin)
                .build());

        int finishCount = 0;
        int totalCount = foreclosedHouses.size();

        for (ForeclosedHouse foreclosedHouse : foreclosedHouses) {
            finishCount ++;
            try {
                foreclosedHouse = selectForeclosedHouseById(foreclosedHouse.getId());
                if (StringUtils.isEmpty(foreclosedHouse.getDescription())) continue;
                String htmlText = CurrencyUtil.htmlTotext(foreclosedHouse.getDescription());

                Pattern pattern = Pattern.compile("建筑面积.\\D{0,20}(\\d+\\.?\\d*)");
                Matcher matcher = pattern.matcher(htmlText.replace("建筑面积", "建筑面积 "));

                BigDecimal mianji = new BigDecimal(0);
                while (matcher.find()) {
                    BigDecimal area = new BigDecimal(matcher.group(1));
                    if (area.compareTo(new BigDecimal(1)) > 0 && area.compareTo(new BigDecimal(10000)) < 0){
                        if (area.compareTo(mianji) > 0){
                            mianji = area;
                        }
                    }
                }

                if (mianji.compareTo(new BigDecimal(0)) == 0 || mianji.intValue() == foreclosedHouse.getBuiltUpAreaSquareCentimeter().intValue()) continue;

                foreclosedHouse.setBuiltUpAreaSquareCentimeter(mianji);
                if (foreclosedHouse.getBuiltUpAreaSquareCentimeter() != null && foreclosedHouse.getBuiltUpAreaSquareCentimeter().compareTo(new BigDecimal(0)) > 0){
                    if (foreclosedHouse.getMarketPriceYuan() != null && foreclosedHouse.getMarketPriceYuan().intValue() > 0){
                        foreclosedHouse.setUnitPriceYuan(new BigDecimal(foreclosedHouse.getMarketPriceYuan()).divide(new BigDecimal(foreclosedHouse.getBuiltUpAreaSquareCentimeter().toString()), BigDecimal.ROUND_HALF_UP).intValue());
                    }
                }
                updateForeclosedHouse(foreclosedHouse);

                BigDecimal areaRate = new BigDecimal(finishCount).divide(new BigDecimal(totalCount), BigDecimal.ROUND_HALF_UP, 2).multiply(new BigDecimal(100));
                log.info("房源编码="+foreclosedHouse.getNameMd5() + ",title="+foreclosedHouse.getTitle()+"，面积修改成功，完成 "+areaRate);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    public void sendSubscribeNotice() {
        try {
            // 发送通知消息
            String appid = configService.selectConfigByKey("biz.wechat.xcx.appid");
            String secret = configService.selectConfigByKey("biz.wechat.xcx.secret");
            String access_token = wechatService.getAccessToken(appid, secret);
            List<Notice> notices = noticeService.selectNoticeListForeclosed(new Notice());

            if (notices != null && notices.size() > 0){
                int threadNum = (notices.size() / 100) + 1;
                threadNum = threadNum > 20 ? 20 : threadNum;
                ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
                notices.forEach(item -> {
                    executorService.execute(() -> {
                        foreclosedOpeningNotice(item, access_token);
                    });
                });

                executorService.shutdown();
                while (true) {
                    Thread.sleep(100);
                    if(executorService.isTerminated()){
                        break;
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void cleanForeclosedHouseStatus() {
        /**
         *          -- 状态修改为已成交
         *          UPDATE fo_foreclosed_house
         *         SET `status` = '已成交'
         *         WHERE
         *             CURRENT_DATE () > end_time
         *         AND (
         *             `status` = '预告中'
         *             OR `status` = '进行中'
         *         )
         */
        // TODO 这个没法改 因为不知道状态是什么了  有可能成交有可能流拍有可能撤销有可能中止
//        foreclosedHouseMapper.batchUpdateStatusEnd();
        /**
         *          -- 状态修改为正在进行
         *          UPDATE fo_foreclosed_house
         *          SET `status` '进行中'
         *          WHERE
         *          NOW() >= start_time
         *          AND NOW() < end_time
         *          AND `status` = '预告中'
         */
        foreclosedHouseMapper.batchUpdateStatusAuctioning();
    }

    @Override
    public void cleanForeclosedHouseStatus1(Long serverId) {
        // 获取时间结束还是进行中或者预告中的数据
        PageUtils.startPage(1, 30);
        List<ForeclosedHouse> foreclosedHouses = selectForeclosedHouseList(Builder.of(ForeclosedHouse::new)
                .with(ForeclosedHouse::setStatusArr, new String[]{"预告中", "进行中"})
                .with(ForeclosedHouse::setEndTime, new Date())
                .with(ForeclosedHouse::setOrigin, "阿里法拍")
                .build());

        ServerManage serverManage = serverManageService.selectServerManageById(serverId);

        int count = detailQueueAdd(serverManage, BizConstants.Spider.ALIDQNAME, BizConstants.Spider.QUEUE_DETAIL_MAX_NUM_ALI, OriginName.ALI.getValue(), foreclosedHouses);
        serverManage.setQueueDetailCount(count);
        serverManageService.updateServerManage(serverManage);

    }

    public int detailQueueAdd(ServerManage serverManage, String queueName, int maxCount, String originName, List<ForeclosedHouse> foreclosedHouses){
        int queueCount = serverQueueCount(queueName + StringUtils.dreX(serverManage.getServerIp()));
        int addNum = 0;
        // 数量小于最大值时才加  否则就不加了
        if (queueCount < maxCount){
            addNum = serverAddDetail(serverManage, queueName, maxCount, originName, foreclosedHouses);
        }
        return queueCount + addNum;
    }

    public int serverQueueCount(String queueName) {
        QueueInformation queueInfo = amqpAdmin.getQueueInfo(queueName);
        if (queueInfo != null) {
            return queueInfo.getMessageCount();
        }
        return 0;
    }

    public int serverAddDetail(ServerManage serverManage, String queueName, Integer addNum, String origin, List<ForeclosedHouse> foreclosedHouses) {
        queueName = queueName + StringUtils.dreX(serverManage.getServerIp());
        for (ForeclosedHouse foreclosedHouse : foreclosedHouses) {
//            rabbitTemplate.convertAndSend(queueName, foreclosedHouse.getAuctionUrl()+"?"+spiderHouse.getId());
            rabbitTemplate.convertAndSend(queueName, foreclosedHouse.getAuctionUrl());
        }
        return foreclosedHouses.size();
    }


    @Override
    public ForeclosedHouse selectForeclosedHouseByCode(String code) {
        return foreclosedHouseMapper.selectForeclosedHouseByCode(code);
    }

    @Override
    public String getForeclosedHouseEstate(ForeclosedHouse foreclosedHouse) {

        String estateName = foreclosedHouse.getAddress(); // TODO 根据地址获取小区  闹腾

        HouseEstate where = Builder.of(HouseEstate::new).with(HouseEstate::setEstateName, estateName).build();

        String deepseekKey = "sk-3e89bfa172744ac49f3b19b987e4b915";



//
//        HouseEstate houseEstate = houseEstateService.selectOneHouseEstate(where);
//
//        if (houseEstate == null){
//            // TODO 小区不存在 添加小区
//            houseEstate = new HouseEstate();
//            houseEstateService.insertHouseEstate(houseEstate);
//        }else {
//            // TODO 如果存在小区判断下更新时间，超过10天了就更新下小区信息
//        }

        return "";
    }


    public void foreclosedOpeningNotice(Notice notice, String access_token){
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token;
        String data = "{\n" +
                "  \"touser\": \""+notice.getOpenId()+"\",\n" +
                "  \"template_id\": \"vSOq9kLt2wrI_Z7pCRHbg5cgCB99HcMK8TdSd89LAm0\",\n" +
                "  \"page\": \"/pages/details/details?id="+notice.getForeclosedHouseId()+"&status=0\",\n" +
                "  \"data\": {\n" +
                "      \"thing1\": {\n" +
                "          \"value\": \""+StringUtils.subString(notice.getTitle(), 0, 15, "...")+"\"\n" +
                "      },\n" +
                "      \"thing2\": {\n" +
                "          \"value\": \""+StringUtils.subString(notice.getAddress(), 0, 15, "...")+"\"\n" +
                "      },\n" +
                "      \"date3\": {\n" +
                "          \"value\": \""+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, notice.getStartTime())+"\"\n" +
                "      } ,\n" +
                "      \"thing4\": {\n" +
                "          \"value\": \"开盘提醒\"\n" +
                "      }\n" +
                "  }\n" +
                "}";

        notice.setStatus(1);
        noticeService.updateNotice(notice);
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.sendPost(url, data);
    }

    public void discountMarkdownNotice(Notice notice, String access_token){
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token;
        String data = "{\n" +
                "  \"touser\": \""+notice.getOpenId()+"\",\n" +
                "  \"template_id\": \"xrGDaKPb7-2Ia_GZQNwQlAU1Bl7M9pz2SeOy6LwpnPM\",\n" +
                "  \"page\": \"/pages/details/details?id="+notice.getDiscountHouseId()+"&status=1\",\n" +
                "  \"data\": {\n" +
                "      \"thing1\": {\n" +
                "          \"value\": \""+StringUtils.subString(notice.getTitle(), 0, 15, "...")+"\"\n" +
                "      },\n" +
                "      \"thing2\": {\n" +
                "          \"value\": \""+StringUtils.subString(notice.getAddress(), 0, 15, "...")+"\"\n" +
                "      },\n" +
                "      \"thing3\": {\n" +
                "          \"value\": \""+notice.getPriceYuan()+"万元\"\n" +
                "      } ,\n" +
                "      \"date4\": {\n" +
                "          \"value\": \""+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, notice.getUpdateTime())+"\"\n" +
                "      }\n" +
                "  }\n" +
                "}";

        HttpRequest httpRequest = new HttpRequest();
        httpRequest.sendPost(url, data);
    }


    // 洗法院数据
    public void clearForeclosedHouseCourt(ForeclosedHouse foreclosedHouse){
        if (StringUtils.isNotEmpty(foreclosedHouse.getAnnouncement())){
            String htmlText = CurrencyUtil.htmlTotext(foreclosedHouse.getAnnouncement());
            if (StringUtils.isNotEmpty(htmlText)){
                String prefixStr = "账户名称：,开户名称：,户名：";
                for (String prefix : prefixStr.split(",")) {
                    Pattern pattern = Pattern.compile(prefix + ".*?([\u4e00-\u9fa5]+)");
                    Matcher matcher = pattern.matcher(htmlText);
                    if (matcher.find()){
                        String court = matcher.group(1);
                        foreclosedHouse.setCourt(court);
                    }
                }
            }
        }
    }

    public void clearForeclosedHouseTimeHandler(ForeclosedHouse foreclosedHouse){
        if (StringUtils.isNotEmpty(foreclosedHouse.getAnnouncement())){
            String htmlText = CurrencyUtil.htmlTotext(foreclosedHouse.getAnnouncement());
            if (StringUtils.isNotEmpty(htmlText)){

                Date[] times = extractStartEndTimeDates(htmlText);

                if (times[0] != null && times[1] != null) {
                    foreclosedHouse.setStartTime(times[0]);
                    foreclosedHouse.setEndTime(times[1]);
                }

            }
        }
    }



    public static String convertChineseTimeTo24h(String timeStr) {
        if (timeStr.contains("上午")) {
            timeStr = timeStr.replace("上午", "日");
            return timeStr;
        } else if (timeStr.contains("下午")) {
            timeStr = timeStr.replace("下午", "日");
            String[] parts = timeStr.split("时");
            int hour = Integer.parseInt(parts[0]);
            hour = (hour < 12) ? hour + 12 : hour;
            return hour + "时" + parts[1];
        }
        return timeStr;
    }

    public static String formatTime(String timeStr) {
        timeStr = convertChineseTimeTo24h(timeStr);
        timeStr = timeStr.replace("时", "").replaceAll("日", " ").replace("起", "").replace("止", "");
        timeStr = timeStr.replaceAll("年|月", "-");
        String daysPattern = ":";
        Pattern pattern = Pattern.compile(daysPattern);
        Matcher matcher = pattern.matcher(timeStr);
        if (matcher.find()) {
            if (timeStr.split(":").length == 1) {
                timeStr += ":00:00";
            } else if (timeStr.split(":").length == 2) {
                timeStr += ":00";
            }
        }else {
            timeStr += "00:00:00";
        }
        return timeStr;
    }

    public static Date parseDateTime(String dateTimeStr) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d H:mm:ss");
        try {
            return formatter.parse(dateTimeStr);
        } catch (ParseException e) {
            formatter = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
            return formatter.parse(dateTimeStr);
        }
    }

    public static Date[] extractStartEndTimeDates(String htmlContent) {
        htmlContent = htmlContent.replace(" ", "").replace("：", ":").replace("起", "").replace("00分", "");
        String timeRangePattern = "(\\d{4}年\\d{1,2}月\\d{1,2}[日]*[上午|下午]*\\d{0,2}[:|起|时|时起]*\\d{0,2})至(\\d{4}年\\d{1,2}月\\d{1,2}[日]*[上午|下午|'']*\\d{0,2}[:|止|时|时止]*\\d{0,2})";
        String datePattern = "(\\d{4}年\\d{1,2}月\\d{1,2}日[上午|下午]*\\d{1,2}时)";
        String daysPattern = "(\\d+)天内";

        Pattern pattern = Pattern.compile(timeRangePattern);
        Matcher matcher = pattern.matcher(htmlContent);

        Date startTime = null;
        Date endTime = null;

        try {
            if (matcher.find()) {
                startTime = parseDateTime(formatTime(matcher.group(1)));
                endTime = parseDateTime(formatTime(matcher.group(2)));
            } else {
                pattern = Pattern.compile(datePattern);
                matcher = pattern.matcher(htmlContent);
                if (matcher.find()) {
                    startTime = parseDateTime(formatTime(matcher.group(1)));
                }
                pattern = Pattern.compile(daysPattern);
                matcher = pattern.matcher(htmlContent);
                if (matcher.find() && startTime != null) {
                    int days = Integer.parseInt(matcher.group(1));
                    endTime = new Date(startTime.getTime() + TimeUnit.DAYS.toMillis(days));
                }else {
                    if (startTime != null){
                        endTime = new Date(startTime.getTime() + TimeUnit.DAYS.toMillis(1));
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return new Date[]{startTime, endTime};
    }

    // 洗来源数据
    public void clearForeclosedHouseOrigin(ForeclosedHouse foreclosedHouse){
        if (StringUtils.isNotEmpty(foreclosedHouse.getAuctionUrl())){
            if (foreclosedHouse.getAuctionUrl().contains(OriginName.ALI.getLabel())){
                foreclosedHouse.setOrigin(OriginName.ALI.getValue());
            }else if (foreclosedHouse.getAuctionUrl().contains(OriginName.JD.getLabel())){
                foreclosedHouse.setOrigin(OriginName.JD.getValue());
            }
        }
    }

    // 洗面积
    public void clearForeclosedHouseMianji(ForeclosedHouse foreclosedHouse){

        // 获取需要发送的数据

    }

    public boolean foreclosedHouseGeocoder(ForeclosedHouse foreclosedHouse){
        try {
            if (StringUtils.isNotEmpty(foreclosedHouse.getAddress())){

                // 腾讯地图
//                HttpRequest httpRequest = new HttpRequest();
//                String url = String.format(BizConstants.GEOCODER_URL, URLEncoder.encode(foreclosedHouse.getAddress().replace("#", "").replace("%", ""), Constants.UTF8));
//                log.info("逆地理编码请求："+ url);
//                HttpRespons httpRespons = httpRequest.sendGet(url);
//                if (httpRespons != null && httpRespons.getCode() == HttpStatus.SUCCESS){
//                    log.info("逆地理编码结果：" + httpRespons.getContent());
//                    JSONObject resultJson = JSONObject.parseObject(httpRespons.getContent());
//                    int status = (int) CurrencyUtil.readJson(resultJson, "status");
//                    if (status == 0){
//                        String lng = String.valueOf(CurrencyUtil.readJson(resultJson, "result.location.lng"));
//                        String lat = String.valueOf(CurrencyUtil.readJson(resultJson, "result.location.lat"));
//                        String province = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.province"));
//                        String city = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.city"));
//                        String district = String.valueOf(CurrencyUtil.readJson(resultJson, "result.address_components.district"));
//                        foreclosedHouse.setLongitude(lng);
//                        foreclosedHouse.setLatitude(lat);
//                        foreclosedHouse.setProvince(province);
//                        foreclosedHouse.setCity(city);
//                        foreclosedHouse.setDistrict(district);
//                        updateForeclosedHouse(foreclosedHouse);
//                    } else if (status == 347 || status == 348){
//                        // 逆不出来
//                        foreclosedHouse.setLongitude("0");
//                        foreclosedHouse.setLatitude("0");
//                        updateForeclosedHouse(foreclosedHouse);
//                    } else if (status == 400){
//                        // 逆不出来
//                        foreclosedHouse.setLongitude("0");
//                        foreclosedHouse.setLatitude("0");
//                        updateForeclosedHouse(foreclosedHouse);
//                    } else {
//                        // 接口次数没了
//                        return false;
//                    }
//                }else {
//                    log.info("逆地理编码失败：" + JSONObject.toJSONString(httpRespons));
//                }

                // 高德地图
                HttpRequest httpRequest = new HttpRequest();
                String url = String.format(BizConstants.AMAP_GEO_URL, URLEncoder.encode(foreclosedHouse.getAddress().replace("#", "").replace("%", ""), Constants.UTF8));
                log.info("逆地理编码请求："+ url);
                HttpRespons httpRespons = httpRequest.sendGet(url);
                if (httpRespons != null && httpRespons.getCode() == HttpStatus.SUCCESS){
                    log.info("逆地理编码结果：" + httpRespons.getContent());
                    JSONObject resultJson = JSONObject.parseObject(httpRespons.getContent());
                    String status = (String) CurrencyUtil.readJson(resultJson, "status");
                    if ("1".equalsIgnoreCase(status)){
                        JSONObject gencodeItem = (JSONObject) CurrencyUtil.readJson(resultJson, "geocodes[0]");
                        if (gencodeItem != null){
                            String location[] = gencodeItem.getString("location").split(",");
                            String lng = location[0];
                            String lat = location[1];
                            String province = gencodeItem.getString("province");
                            String city = gencodeItem.getString("city");
                            String district = gencodeItem.getString("district");
                            foreclosedHouse.setLongitude(lng);
                            foreclosedHouse.setLatitude(lat);
                            foreclosedHouse.setProvince(province);
                            foreclosedHouse.setCity(city);
                            foreclosedHouse.setDistrict(district);
                            foreclosedHouse.setAddress(gencodeItem.getString("formatted_address"));
                            updateForeclosedHouse(foreclosedHouse);
                        }

                    }
//                    else if (status == 347 || status == 348){
//                        // 逆不出来
//                        foreclosedHouse.setLongitude("0");
//                        foreclosedHouse.setLatitude("0");
//                        updateForeclosedHouse(foreclosedHouse);
//                    } else if (status == 400){
//                        // 逆不出来
//                        foreclosedHouse.setLongitude("0");
//                        foreclosedHouse.setLatitude("0");
//                        updateForeclosedHouse(foreclosedHouse);
//                    }
                    else {
                        // 接口次数没了
                        return false;
                    }
                }else {
                    log.info("逆地理编码失败：" + JSONObject.toJSONString(httpRespons));
                }

            }else {
                if (StringUtils.isEmpty(foreclosedHouse.getTitle())){
                    deleteForeclosedHouseById(foreclosedHouse.getId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }


    private static final String API_KEY = "cd61c5804880ef3a80a917e7fbf942a1";
    private static final String API_URL = "https://restapi.amap.com/v3/geocode/geo?address=%s&key=" + API_KEY;

    public static String getCommunityName(String address) {
        String apiUrl = "https://api.deepseek.com/v1/chat/completions";
        String deepseekKey = "sk-3e89bfa172744ac49f3b19b987e4b915";
        String prompt = "{\n" +
                "        \"model\": \"deepseek-chat\",\n" +
                "        \"messages\": [\n" +
                "          {\"role\": \"system\", \"content\": \"地址："+address+"，请根据以上地址，提取出小区名称,结果以json格式返回，code=0：成功获取到，code=1：获取失败，data=小区名称\"},\n" +
                "          {\"role\": \"user\", \"content\": \"深圳市橙创蓝谷科技有限公司\"}\n" +
                "        ],\n" +
                "        \"stream\": false\n" +
                "      }";


        System.out.println(prompt);
        try {
            HttpRequest httpRequest = new HttpRequest();
            httpRequest.addHeader("Authorization", "Bearer " + deepseekKey);
            httpRequest.addHeader("Content-Type", "application/json");
            HttpRespons response = httpRequest.sendPost(apiUrl, prompt);
            if (response != null && response.getCode() == 200) {
                System.out.println(response.getContent());
//                JSONObject jsonResponse = JSONObject.parseObject(response.getContent());
                return response.getContent();
            } else {
                System.out.println("Error: Unable to retrieve community name from DeepSeek API.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        return null;

    }

    public static void main(String[] args) {

        getCommunityName("哈尔滨市香坊区进乡街120号");

//        // Example HTML content (replace with actual content)
//        String htmlContent = "本院）将于2021年10月28上午10时至2021年10月29上午10时止（延时除外）在本院淘宝";
//
//
//        // Call the function to extract start and end time
//        Date[] times = extractStartEndTimeDates(htmlContent);
//
//        if (times[0] != null && times[1] != null) {
//            System.out.println("Start Time: " + times[0]);
//            System.out.println("End Time: " + times[1]);
//            Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, "2018-07-2 10:00:00");
//            System.out.println(date);
//        } else {
//            System.out.println("No match found.");
//        }



    }
}
